package top.saycode.schedule.base.mapper;

import top.saycode.schedule.base.common.BaseProperties;
import top.saycode.schedule.base.model.TaskDO;
import static top.saycode.schedule.base.sql.TaskSQL.*;

import java.sql.*;
import java.util.List;

/**
 * @author <a href="https://gitee.com/LongLiS">cloudconceal</a> 2025/3/25 13:37
 */

public class TaskScheduleMapper {

    private final Connection sqlLiteConn;

    private TaskScheduleMapper() {
        try {
            sqlLiteConn = DriverManager.getConnection("jdbc:sqlite:" + BaseProperties.DB_PATH);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static volatile TaskScheduleMapper instance;

    public static TaskScheduleMapper getInstance() {
        if(instance == null) {
            synchronized (TaskScheduleMapper.class) {
                if(instance == null) {
                    instance = new TaskScheduleMapper();
                }
            }
        }

        return instance;
    }

    public void initTableIfNotExist() {
        try {
            sqlLiteConn.createStatement().execute(TABLE);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public List<TaskDO> selectAll() {
        try (ResultSet resultSet = sqlLiteConn.createStatement().executeQuery(SELECT_ALL)){
            return convertTaskSchedule(resultSet);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void insert(TaskDO taskDO) {
        try (PreparedStatement prep = sqlLiteConn.prepareStatement(INSERT)){
            fillInsertParams(prep, taskDO);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
